# Copyright 2022. All Rights Reserved.
# Author: Bruce-Lee-LY
# Date: 16:19:40 on Sun, May 29, 2022
#
# Description: compile script

#!/bin/bash

set -euo pipefail

echo "========== build enter =========="

WORK_PATH=$(cd $(dirname $0) && pwd) && cd $WORK_PATH

CUDA_ARCHITECTURE=89 # a: (Tesla P100: 60, GTX1080Ti: 61, Tesla V100: 70, RTX2080Ti: 75, NVIDIA A100: 80, RTX3080Ti / RTX3090 / RTX A6000: 86, RTX4090: 89, NVIDIA H100: 90)
# BUILD_TYPE=Debug # t: (Debug, Release)
BUILD_TYPE=Release # t: (Debug, Release)
WITH_SAMPLE=ON # s: (ON, OFF)
VERBOSE_MAKEFILE=OFF # b: (ON, OFF)

while getopts ":a:t:s:b:" opt
do
    case $opt in
        a)
        CUDA_ARCHITECTURE=$OPTARG
        echo "CUDA_ARCHITECTURE: $CUDA_ARCHITECTURE"
        ;;
        t)
        BUILD_TYPE=$OPTARG
        echo "BUILD_TYPE: $BUILD_TYPE"
        ;;
        s)
        WITH_SAMPLE=$OPTARG
        echo "WITH_SAMPLE: $WITH_SAMPLE"
        ;;
        b)
        VERBOSE_MAKEFILE=$OPTARG
        echo "VERBOSE_MAKEFILE: $VERBOSE_MAKEFILE"
        ;;
        ?)
        echo "invalid param: $OPTARG"
        exit 1
        ;;
    esac
done

echo_cmd() {
    echo $1
    $1
}

echo "========== build cuda_hook =========="

echo_cmd "rm -rf build"
echo_cmd "mkdir build"

echo_cmd "cd build"
echo_cmd "cmake -DCMAKE_CUDA_ARCHITECTURES=$CUDA_ARCHITECTURE -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DHOOK_WITH_SAMPLE=$WITH_SAMPLE -DHOOK_VERBOSE_MAKEFILE=$VERBOSE_MAKEFILE -DCMAKE_INSTALL_PREFIX=$WORK_PATH -DCMAKE_SKIP_RPATH=ON .."
echo_cmd "make -j$(nproc --ignore=2)"
echo_cmd "make install"

echo "========== create soft link =========="

# cuda
echo_cmd "ln -s libcuda_hook.so libcuda.so.1"
echo_cmd "ln -s libcuda.so.1 libcuda.so"

# cudart
echo_cmd "ln -s libcuda_hook.so libcudart.so.11.0"
echo_cmd "ln -s libcudart.so.11.0 libcudart.so"

# cublas
echo_cmd "ln -s libcuda_hook.so libcublas.so.11"
echo_cmd "ln -s libcublas.so.11 libcublas.so"


echo_cmd "cp -d *.so *.so.* $WORK_PATH/lib64"


echo "========== build exit =========="
